<?php 
namespace app\wework\controller\h5;

use app\wework\controller\Base;
use think\facade\Db;
use app\wework\model\BaseModel;
use app\wework\model\user\promotion\BuffetPromotionModel;
use app\wework\model\Wxopenapi;
use app\wework\model\QyWechatApi;
use app\wework\model\JsSdk;
use think\facade\Log;
use app\wework\model\Helper;
use think\facade\View;
require "../extend/Phpqrcode/phpqrcode.php";



/**
 * 自助推广码 h5端
*/
class BuffetPromotion extends Base{
	public function index(){
		$code = $this->req->param("code");
		$id = $this->req->param("id");
		$promotion = BuffetPromotionModel::info($id);
		$wid = $promotion["wid"];
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$wid = $config["wid"];
		if($code){
			$resArr = QyWechatApi::getuserinfo($wid,$code);
			if(!isset($resArr['UserId'])) return view("show");
			$staffs = $promotion["staffs"];
			$where["wid"] = $wid;
			$where["userid"] = $resArr["UserId"];
			$staff = Helper::getUser($where);
			if(!in_array($staff["id"], $staffs)) return view("show");
			$code = new \QRcode();
			$path = '../public/static/wework/promotion/';
			if(!file_exists($path))mkdir($path,0777,true);
			$url = $this->req->domain()."/wework/h5.BuffetPromotion/customer.html?id=".$id."&staff_id=".$staff["id"];
		    $res = $code->png($url,$path.$promotion["name"]."-".$staff["id"].".png", 6);
		    if(!$res)$res = $this->req->domain()."/static/wework/promotion/".$promotion["name"]."-".$staff["id"].".png";
		    if($promotion["h5_type"] == 2){
		        $promotion['h5_tow_style']['tops'] = $promotion['h5_tow_style']['tops']*1.8;
			    $promotion['h5_tow_style']['left'] = $promotion['h5_tow_style']['left']*1.8;
		    }
			View::assign("staff", $staff);
			View::assign("user_index", 0);
			View::assign("unionid", 0);
			View::assign("staff_id", 0);
			View::assign("promotion", $promotion);
			View::assign("urls", $this->req->domain()."/wework/h5.BuffetPromotion/customer.html?id=".$id."&staff_id=".$staff["id"]);
			View::assign("qrcode", $res);
			if($promotion['h5_type'] == 2) return view();
			if($promotion['h5_type'] == 1) return view("default");
			return view();
		}else{
			$redirect_uri = urlencode($this->req->domain().'/wework/h5.BuffetPromotion/index.html?id='.$id);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			return redirect($url);
		}
	}


	public function customer(){
		$id = $this->req->param("id");
		$promotion = BuffetPromotionModel::info($id);
		$staff_id = $this->req->param("staff_id");
		 if($promotion["h5_type"] == 2){
	        $promotion['h5_tow_style']['tops'] = $promotion['h5_tow_style']['tops']*1.8;
		    $promotion['h5_tow_style']['left'] = $promotion['h5_tow_style']['left']*1.8;
	    }
		$wid = $promotion["wid"];
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$open_confing = Wxopenapi::openConfing($wid);
		$authorizer_info = Db::table("kt_wework_authorizer_info")->where(["wid"=>$wid,"type"=>1])->find();
		if($this->req->get('code')){
			$code = $this->req->get('code');
			$token = Wxopenapi::getComponentAccessToken($wid);
			$url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token?appid='.$authorizer_info["authorizer_appid"].'&code='.$code.'&grant_type=authorization_code&component_appid='.$open_confing["app_id"].'&component_access_token='.$token;
			$res_arr = json_decode(curlGet($url),1);
			$urls = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$res_arr["access_token"].'&openid='.$res_arr['openid'].'&lang=zh_CN';
			$res = json_decode(curlGet($urls),1);
			View::assign("id", $id);
			View::assign("customer", 1);
			View::assign("promotion", $promotion);
			//统计浏览次数
			$data["wid"] = $wid;
			$data["pid"] = $id;
			$data["staff_id"] = $staff_id;
			$data["unionid"] = $res["unionid"];
			$data["headimgurl"] = $res["headimgurl"];
			$data["nickname"] = $res["nickname"];
			$data["ctime"] = date("Y-m-d H:i:s");
			$data["type"] = 1;
			Db::table("kt_wework_promotion_size")->insertGetId($data);
			if($promotion["type"] == 1){
				$code = $promotion["qr_code"];
			}else{
				$size = Db::table("kt_wework_promotion_size")->where(["unionid"=>$res["unionid"],"pid"=>$id,"wid"=>$wid,"status"=>2])->find();
				$group_data = json_decode($promotion["group_data"],1);
				if($size){
					if($size["group_id"]){
	            		$res = $this->getGroupData($size["group_id"],$wid);
	            		$unionids = array_column($res, "unionid");
	            		if(in_array($size["unionid"],$unionids)){
	            			View::assign("text", "您已加入该规则的群聊，请勿重复操作");
	        				return view("show");
	            		}
					}
					if($size["staff_id"] != $staff_id){
						View::assign("text", "您已绑定改规则的其他客服人员，请勿重复操作");
        				return view("show");
					}
				}
				for ($i=0; $i < count($group_data); $i++) {
        		    $group_id = $group_data[$i]["id"];
            		$res = $this->getGroupData($group_id,$wid);
            		if(count($res) >= $group_data[$i]["size"]){
            			if(!$group_data[$i+1]["id"]){
            				$Promotion->status = 3;
            				Db::table("kt_wework_promotion")->where(["id"=>$id])->update(["status"=>3]);
            				View::assign("text", "改活动已结束");
            				return view("show");
            			    break;
            			}
            			$group_id = $group_data[$i+1]["id"];
    					$code = $group_data[$i+1]["code"];
            			$group_data[$i+1]["status"] = 2;
            			$group_data[$i]["status"] = 3;
            			break;
            		}else{
    				    $code = $group_data[$i]["code"];
    				    break;
            		}
				}
				Db::table("kt_wework_promotion")->where(["id"=>$id])->update(["group_data"=>json_encode($group_data,320)]);
				$sizes["wid"] = $wid;
				$sizes["pid"] = $id;
				$sizes['staff_id'] = $staff_id;
				$sizes['unionid'] = $res["unionid"];
				$sizes['headimgurl'] = $res["headimgurl"];
				$sizes['nickname'] = $res["nickname"];
				$sizes["ctime"] = date("Y-m-d H:i:s");
				$sizes['type'] = 1;
				$sizes['status'] = 2;
				$sizes['group_id'] = $group_id;
				if(!$size)Db::table("kt_wework_promotion_size")->insertGetId($sizes);
				if($size)Db::table("kt_wework_promotion_size")->where(["id"=>$size["id"]])->save($sizes);
				View::assign("unionid", $res["unionid"]);
				View::assign("promotion", $promotion);
				View::assign("staff_id", $staff_id);
				View::assign("qrcode", $code);
				if($promotion->h5_type == 2) return view("index");
				if($promotion->h5_type == 1) return view("default");
			}
		}else{
			$redirect_uri = urlencode($this->req->domain()."/wework/h5.BuffetPromotion/customer.html?id=".$id."&staff_id=".$staff_id);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$authorizer_info["authorizer_appid"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=STATE&component_appid='.$open_confing["app_id"].'#wechat_redirect';
			return redirect($url);
		}
	}

	public function getGroupData($id,$wid){
		$group = Db::table("kt_wework_group")->where(["wid"=>$wid,"id"=>$id])->find();
		$group = Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$group["chat_id"]])->select()->toArray();

		return $group;
	}
}